# -*- coding: utf-8 -*-
import time
import io
import sys
import re
from db_conn import *
from datetime import datetime,timedelta
from anatel_utils import updateTable
from warnings import filterwarnings

filterwarnings('error', category=MySQLdb.Warning)

date_now = datetime.now()
in_file_name_1 = "" + date_now.strftime("%Y-%m-%d") + "_file1.txt" #FILE DIFF NEW
in_file_name_2 = "" + date_now.strftime("%Y-%m-%d") + "_file2.txt" #FILE DIFF OLD
export_file_id = "" + date_now.strftime("%Y-%m-%d") + "-export-db-id.txt"
export_file = "" + date_now.strftime("%Y-%m-%d") + "-export-db.txt"
double_check_file = "" + date_now.strftime("%Y-%m-%d") + "-double_check.txt"
atualizar_global=1
#saida_arr = []

##CONFIGURACAO DE PARAMETROS DE AFINACAO
distancia_minima = 3
threshold_menor = 50
threshold_maior = 80
threshold_fields_change = 10

def updateDb(update_query,id_ant=0):
    #realmente onde atualiza
    cursor,conn = db_connect()
    try:
        cursor.execute(update_query)
        #pass
    except MySQLdb.Warning, e:
        # handle warnings, if the cursor you're using raises them
        #print str(e)
        print "Warning id_antena=%s - %s" % (id_ant,e)
        #arr_campo = re.findall("'([^']*)'", str(e));
    except:
        print "Erro ao atualizar o banco"
    finally:
        db_disconnect(cursor,conn)

def getAntenaId(line_txt,search_table='anatel_import'):
    try:
        cursor,conn = db_connect()
        count_ln=0
        
        #field_names = {}
        #for i in range(len(cursor.description)):
        #    field_names[cursor.description[i][0]]=i-1
        #print field_names     
        field_names = ['TransmissaoInicial',
                         'UnidadeFrequenciaTX',
                         'RecepcaoInicial',
                         'UnidadeFrequenciaRX',
                         'Situacao',
                         'CaraterSecundario',
                         'IndConfidencial',
                         'TipoClasseEstacao',
                         'Horarios',
                         'DesignacaoEmissao',
                         'PotenciaOperacao',
                         'UnidadePotencia',
                         'Equipamento',
                         'TipoAntena',
                         'EquipamentoAntena',
                         'Ganho',
                         'FrenteCosta',
                         'AnguloMeiaPotencia',
                         'AnguloElevacao',
                         'Azimute',
                         'VariacaoAzimutal',
                         'TipoPolarizacao',
                         'Altura',
                         'Raio',
                         'Latitude',
                         'Longitude',
                         'Altitude',
                         'Estacao',
                         'Servico',
                         'Indicativo',
                         'MedPotenciaMaxima_TR',
                         'MedLarguraBanda',
                         'DiametroSGCH',
                         'Diagrama',
                         'SiglaEstacao_TRS',
                         'LongitudeOrbitalSubida',
                         'NomeFeixeSubida',
                         'SiglaEstacaoDescida',
                         'LongitudeOrbitalDescida',
                         'NomeFeixeDescida',
                         'TipoEstacao',
                         'NomeEntidade',
                         'NumEntidade',
                         'NomeMunicipio',
                         'CodMunicipio',
                         'Endereco',
                         'UF',
                         'TipoClasseCorrespondencia',
                         'Rede',
                         'Distancia',]
        dict_fields={}        
        for f in range(len(field_names)):
            dict_fields[field_names[f]]=f

        line = line_txt 
                
        #start_parcial_select = time.time()
        
        select_values = ""
        line_fix = line.replace("\r","").replace("\n","").split("|")
        for col in range(len(line_fix)):
            #insert_values += """'%s',""" % (re.escape(col))
            #insert_values += """'%s',""" % (str(MySQLdb.escape_string(col)))
            #select_values += """%s = '%s' and """ % (field_names[col],str(MySQLdb.escape_string(line_fix[col])))
            if len(str(line_fix[col]).strip()) > 0:
                select_values += """%s = '%s' and """ % (field_names[col],str(MySQLdb.escape_string(line_fix[col])))
        
        select_anatel="""
        SELECT id_antena from %s
        where 
        %s
        1 = 1
        """ % (search_table,select_values)
        #print select_anatel
        try:
            #print select_anatel
            cursor.execute(select_anatel)
            resp = cursor.fetchall()
            if len(resp)>0:
                for r in resp:
                    return str(r[0])
            else:
                return "0"
        except MySQLdb.Warning, e:
            # handle warnings, if the cursor you're using raises them
            arr_campo = re.findall("'([^']*)'", str(e));
            print arr_campo
            print line.split("|")[int(dict_fields[arr_campo[0].replace("'","")])]    
        except:
            print "Erro ao atualizar o banco"
            
        #print "(Tempo Gasto Select: %s)" % ((time.time() - start_parcial_select))
        
        #start_parcial_linux = time.time()
        
        #print getDbIdFunc(line.replace("\r","").replace("\n",""))
        
        #print "(Tempo Gasto Linux: %s)" % ((time.time() - start_parcial_linux))
        
        count_ln+=1
        if count_ln%1000==0:
            print "Counter: %s" % (count_ln)
        db_disconnect(cursor,conn)
    except:
        print "Erro ao atualizar o banco"

def getLineByNumber(line_nbr,file_name):
    linesByNbr=execServerLit("sed -n '%sp' %s" % (line_nbr,file_name))
    #print "linesByNbr: %s" % linesByNbr
    return linesByNbr

'''
def getDbId(s1):
    exp_file_id = open(export_file_id)
    for linha_exp in exp_file_id.readlines():
        if linha_exp.find(s1.replace("\n","")) > -1:
            return linha_exp.split("|")[-1]
'''
'''
def getDbIdGrep(s1):
    resposta=execServerLit('grep -F "%s" %s' % (s1.replace("\n",""),export_file_id))    
    try:
        return str(resposta).split("|")[-1]
    except:
        return "0"
'''
def getDbIdFunc(line):   
    try:
        func = getLineByNumber(getMatchedLine(line,export_file),export_file_id)
        #print "func: %s" % func
        return func.split("|")[-1]
    except:
        return "0"
    
def getLineCount(file_name):
    linesCount=execServerLit('wc -l %s' % (file_name))
    return linesCount

def delMatchedLine(line_nbr,file_name):
    execServerLit("sed --in-place '%sd' %s" % (line_nbr,file_name)) 

'''
def getDelLine(s1):
    resposta=execServerLit('grep -n -F "%s" %s' % (s1.replace("\n",""),in_file_name_2))    
    try:
        return str(resposta).split(":")[0]
    except:
        return 0
'''
     
def getMatchedLine(s1,file_name):
    resposta=execServerLit('grep -n -F "%s" %s' % (s1.replace("\n",""),file_name))    
    try:
        return str(resposta).split(":")[0]
    except:
        return 0    


def execServerLit(command):
    import os
    #print command
    execute_command = os.popen(command,"r")
    return execute_command.read()

def distancia_check(menor_distancia,s1,linha_menor_distancia):
    if menor_distancia > threshold_menor: #threshold de 30
        if menor_distancia < threshold_maior:  ##entra aqui os casos que estao no meio termo entre os threshhold menor e maior, entao eh feita uma segunda verificacao##
            if ((s1.split("|")[19] == linha_menor_distancia.split("|")[19]) and (s1.split("|")[27] == linha_menor_distancia.split("|")[27])): #Azimute e estacao iguais
                print "> Azimute e Estacao Iguais, Identificado como alteracao"
                colunas_check(s1,linha_menor_distancia)
            else:
                # mais uma chance caso a estacao e endereco seja igual atualiza.
                if ((s1.split("|")[27] == linha_menor_distancia.split("|")[27]) and (s1.split("|")[45].lower() == linha_menor_distancia.split("|")[45].lower())):
                    atua = 1
                    print "> Estacao e Endereco igual, atualiza"
                # caso lat e long e endereco for diferente, nao atualiza e nao joga em double
                elif ((s1.split("|")[24] != linha_menor_distancia.split("|")[24]) and (s1.split("|")[25] != linha_menor_distancia.split("|")[25]) and (s1.split("|")[45].lower() != linha_menor_distancia.split("|")[45].lower())):
                    atua = 0
                    print "> lat e long e endereco sao diferentes, nao atualiza e nao joga em double. Eh saida"
                    return 1000, s1
                else:
                    atua = 0 
                    print "> Parece Saida! Double Check! Nao atualiza"
                    
                    id_antena = getAntenaId((linha_menor_distancia))
                    
                    insert_values = ""
                    for col in s1.replace("\r","").replace("\n","").split("|"):
                        if len(str(MySQLdb.escape_string(col)))>0:
                            insert_values += ",'%s'" % (str(MySQLdb.escape_string(col)))
                        else:
                            insert_values += ',NULL'
                                                
                    insert_anatel="""
                    insert into anatel_double_check
                    values(%s%s,'%s-new',NULL);
                    """ % (id_antena,insert_values,in_file_name_1)
                    
                    print insert_anatel
                    
                    cursor,conn = db_connect()
                    try:
                        #print insert_anatel
                        cursor.execute(insert_anatel) 
                        delMatchedLine(getMatchedLine(s1,in_file_name_1),in_file_name_1)#apaga do arquivo new mesmo assim pra não ser considerado insert               
                    except:
                        print "Erro ao atualizar o banco para double"
                    finally:
                        db_disconnect(cursor,conn)     
                    
                    ############################DOUBLE 
                    insert_values = ""
                    for col in linha_menor_distancia.replace("\r","").replace("\n","").split("|"):
                        if len(str(MySQLdb.escape_string(col)))>0:
                            insert_values += ",'%s'" % (str(MySQLdb.escape_string(col)))
                        else:
                            insert_values += ',NULL'
                                                
                    insert_anatel="""
                    insert into anatel_double_check
                    values(%s%s,'%s-old',NULL);
                    """ % (id_antena,insert_values,in_file_name_2)
                    
                    print insert_anatel
                    
                    cursor,conn = db_connect()
                    try:
                        #print insert_anatel
                        cursor.execute(insert_anatel)
                        delMatchedLine(getMatchedLine(linha_menor_distancia,in_file_name_2),in_file_name_2)#apaga do arquivo old mesmo assim pra não ser considerado delete         
                    except:
                        print "Erro ao atualizar o banco para double"
                    finally:
                        db_disconnect(cursor,conn)                                                 
                
                                    
                    #escreve em um arquivo para analise posterior
                    file_id = open(double_check_file, "a")
                    file_id.write(s1+"\n")
                    file_id.write(linha_menor_distancia+"\n")
                    file_id.write("\n\n")
                    file_id.close()
                colunas_check(s1,linha_menor_distancia, atua)
                #saida_arr.append(s1)
                return menor_distancia, linha_menor_distancia
        else:
            #print "> Saida"
            #saida_arr.append(s1)
            return 1000, s1
        
    else: #identifica campo
        colunas_check(s1,linha_menor_distancia)
                        
    return menor_distancia,linha_menor_distancia    
def situacao_check(valor_new,valor_old):
    print "Mudanca de Situacao de '%s' para '%s'" % (valor_old.split("|")[4],valor_new.split("|")[4])
    #id_antena = getDbIdFunc(line)
    id_antena = getAntenaId(valor_old)
    print "Situacao id_antena=%s" % (id_antena)
    #delete_line_file2 = getMatchedLine(line,in_file_name_2)
    #delete_line_file1 = getMatchedLine(s1,in_file_name_1)
    update_query = "update `laguardia`.`anatel_import` set Situacao='%s' WHERE id_antena=%s" % (valor_new.split("|")[4],id_antena)
    print "Query: %s" % (update_query) 
    #print "Delete Line File2: %s" % (delete_line_file2)
    #print "Delete Line File1: %s" % (delete_line_file1)
    if atualizar_global:
        delMatchedLine(getMatchedLine(valor_old,in_file_name_2),in_file_name_2)
        delMatchedLine(getMatchedLine(valor_new,in_file_name_1),in_file_name_1)    
        updateTable(id_antena,2,'Situacao',valor_old.split("|")[4],valor_new.split("|")[4])
        updateDb(update_query)    
    '''
    if delete_line_file2 and delete_line_file1: 
        delMatchedLine(delete_line_file2,in_file_name_2)
        delMatchedLine(delete_line_file1,in_file_name_1)
        updateTable(id_antena,2,'Situacao',s1.split("|")[4],line.split("|")[4])
        updateDb(update_query)
    else:
        print "Erro - alguma das linhas não encontrada."   
    '''
     
    return 0,valor_old
            
def colunas_check(s1,linha_menor_distancia, atualizar = 1):
    counter_fields_change = 0    
    #id_antena = getDbIdFunc(linha_menor_distancia)
    id_antena = getAntenaId((linha_menor_distancia))
    print "id_antena: %s" % (id_antena)
    hearders = 'TransmissaoInicial|UnidadeFrequenciaTX|RecepcaoInicial|UnidadeFrequenciaRX|Situacao|CaraterSecundario|IndConfidencial|TipoClasseEstacao|Horarios|DesignacaoEmissao|PotenciaOperacao|UnidadePotencia|Equipamento|TipoAntena|EquipamentoAntena|Ganho|FrenteCosta|AnguloMeiaPotencia|AnguloElevacao|Azimute|VariacaoAzimutal|TipoPolarizacao|Altura|Raio|Latitude|Longitude|Altitude|Estacao|Servico|Indicativo|MedPotenciaMaxima_TR|MedLarguraBanda|DiametroSGCH|Diagrama|SiglaEstacao_TRS|LongitudeOrbitalSubida|NomeFeixeSubida|SiglaEstacaoDescida|LongitudeOrbitalDescida|NomeFeixeDescida|TipoEstacao|NomeEntidade|NumEntidade|NomeMunicipio|CodMunicipio|Endereco|UF|TipoClasseCorrespondencia|Rede|Distancia'
    hearders_arr = hearders.split("|")
    #linha_menor_distancia_arr = linha_menor_distancia.split("|")
    #s1_arr_b = s1.split("|")
          
    update_query="update  `laguardia`.`anatel_import` set "
    
    #necessario atualizar o counter primeiro pra usar a qtd de campos como condicao
    for i in range(len(hearders_arr)):        
        if s1.split("|")[i].strip()!=linha_menor_distancia.split("|")[i].strip():
            counter_fields_change+=1

    #Se situacao da nova for Inclusao e qtd alterada de campos grande, nao atualiza
    if ((counter_fields_change>threshold_fields_change) and s1.split("|")[4].strip().lower().find('incl')>-1):
        atualizar=0 #como eh uma checagem interna da funcao, usamos a var local atualizar
    #Se a qtd de campos mais lat e long e endereco forem diferentes, nao atualiza
    if ((counter_fields_change>threshold_fields_change) and (s1.split("|")[24] != linha_menor_distancia.split("|")[24]) and (s1.split("|")[25] != linha_menor_distancia.split("|")[25]) and (s1.split("|")[45].lower() != linha_menor_distancia.split("|")[45].lower())):
        atualizar=0 #como eh uma checagem interna da funcao, usamos a var local atualizar
        
    if atualizar and atualizar_global:    
            
        for i in range(len(hearders_arr)):        
            if s1.split("|")[i].strip()!=linha_menor_distancia.split("|")[i].strip():
                #update_query=update_query+"%s='%s'," % (hearders_arr[i],re.escape(s1.split("|")[i]))
                update_query=update_query+"%s='%s'," % (hearders_arr[i],MySQLdb.escape_string(s1.split("|")[i]))
                print "De %s: '%s'" % (hearders_arr[i],linha_menor_distancia.split("|")[i])
                print "Para %s: '%s'" % (hearders_arr[i],s1.split("|")[i])
                #updateTable(id_antena,2,hearders_arr[i],re.escape(linha_menor_distancia.split("|")[i]),re.escape(s1.split("|")[i]))
                updateTable(id_antena,2,hearders_arr[i],MySQLdb.escape_string(linha_menor_distancia.split("|")[i]),MySQLdb.escape_string(s1.split("|")[i]))
                
        #delete_line_file2 = getMatchedLine(linha_menor_distancia,in_file_name_2)
        #delete_line_file1 = getMatchedLine(s1,in_file_name_1)
        #remove a ultima virgula
        update_query=update_query[:-1]+" WHERE id_antena="+id_antena

        print "Qtd de campos atualizados: %s (%s)" % (counter_fields_change,id_antena)
        print "Query: %s" % (update_query) 
        #print "Delete Line File2: %s" % (delete_line_file2)
        #print "Delete Line File1: %s" % (delete_line_file1)
        
        delMatchedLine(getMatchedLine(linha_menor_distancia,in_file_name_2),in_file_name_2)
        delMatchedLine(getMatchedLine(s1,in_file_name_1),in_file_name_1)            
        updateDb(update_query,id_antena)
        
        '''
        if delete_line_file2 and delete_line_file1: 
            delMatchedLine(delete_line_file2,in_file_name_2)
            delMatchedLine(delete_line_file1,in_file_name_1)            
            updateDb(update_query)
        else:
            print "Erro - alguma das linhas não encontrada."          
        '''
    
def levenshtein(s1, s2):
    s1 = s1.lower()
    s2 = s2.lower()
    if len(s1) < len(s2):
        return levenshtein(s2, s1)
    if not s1:
        return len(s2)
 
    previous_row = xrange(len(s2) + 1)
    for i, c1 in enumerate(s1):
        current_row = [i + 1]
        for j, c2 in enumerate(s2):
            insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
            deletions = current_row[j] + 1       # than s2
            substitutions = previous_row[j] + (c1 != c2)
            current_row.append(min(insertions, deletions, substitutions))
        previous_row = current_row
 
    return previous_row[-1]

"""

def levenshtein(seq1, seq2):
    oneago = None
    thisrow = range(1, len(seq2) + 1) + [0]
    for x in xrange(len(seq1)):
        twoago, oneago, thisrow = oneago, thisrow, [0] * len(seq2) + [x + 1]
        for y in xrange(len(seq2)):
            delcost = oneago[y] + 1
            addcost = thisrow[y - 1] + 1
            subcost = oneago[y - 1] + (seq1[x] != seq2[y])
            thisrow[y] = min(delcost, addcost, subcost)
    return thisrow[len(seq2) - 1]

def levenshtein(a,b):
    "Calculates the Levenshtein distance between a and b."
    n, m = len(a), len(b)
    if n > m:
        # Make sure n <= m, to use O(min(n,m)) space
        a,b = b,a
        n,m = m,n
        
    current = range(n+1)
    for i in range(1,m+1):
        previous, current = current, [i]+[0]*n
        for j in range(1,n+1):
            add, delete = previous[j]+1, current[j-1]+1
            change = previous[j-1]
            if a[j-1] != b[i-1]:
                change = change + 1
            current[j] = min(add, delete, change)
            
    return current[n]
"""
'''
def levenshtein_file(s1, file_s2, same_fields):
    #print "levenshtein_file"
    file_s2_io  = open(file_s2, "rb")
    
    menor_distancia = 1000 #grande o suficiente pra ser ultima
    linha_menor_distancia = ''
    
    for line in file_s2_io.readlines():
        line = line.strip().replace("\r","").replace("\n","")
        
        for x in same_fields:
            #print "Condicao %s" % (x)
            if not (s1.split("|")[x] == line.split("|")[x]):
                continue
            
        #check situacao e jah retorna em caso de ser essa a mudanca
        if ( ("".join(s1.split("|")[:3])+"".join(s1.split("|")[5:])) == ("".join(line.split("|")[:3])+"".join(line.split("|")[5:])) and (s1.split("|")[4] != line.split("|")[4]) ):
            print "Situacao DEBUG: s1='%s' - line='%s'" % (s1.split("|")[4],line.split("|")[4]) 
            return situacao_check(s1, line)
        
        distancia_comp = levenshtein(s1, line)
        #print distancia_comp
        
        if distancia_comp < menor_distancia:
            menor_distancia = distancia_comp
            linha_menor_distancia = line
            #se a distancia for muito pequena, dá como achado, e sai do loop
            if (menor_distancia < distancia_minima):
                break
            
    return distancia_check(menor_distancia,s1,linha_menor_distancia)
'''
def levenshtein_txt(s1, txt_s2):
    #print "levenshtein_file"    
    menor_distancia = 1000 #grande o suficiente pra ser ultima
    linha_menor_distancia = ''
    
    for line in txt_s2.split("\n"):
        line = line.strip().replace("\r","").replace("\n","")

        #check situacao e jah retorna em caso de ser essa a mudanca
        if ( ("".join(s1.split("|")[:4])+"".join(s1.split("|")[5:])) == ("".join(line.split("|")[:4])+"".join(line.split("|")[5:])) and (s1.split("|")[4] != line.split("|")[4]) ):
            #print "Situacao DEBUG: s1='%s' - line='%s'" % (s1.split("|")[4],line.split("|")[4]) 
            return situacao_check(s1, line)
        elif ( ("".join(s1.split("|")[:4])+"".join(s1.split("|")[5:])) == ("".join(line.split("|")[:4])+"".join(line.split("|")[5:])) and (s1.split("|")[4] == line.split("|")[4]) ):
            #igualzinho
            return 0,line
            
        distancia_comp = levenshtein(s1, line)
        #print distancia_comp
        
        if distancia_comp < menor_distancia:
            menor_distancia = distancia_comp
            linha_menor_distancia = line
            #se a distancia for muito pequena, dá como achado, e sai do loop
            if (menor_distancia < distancia_minima):
                break
            
    return distancia_check(menor_distancia,s1,linha_menor_distancia)        
        
def levenshtein_file_file(file_s1, file_s2):
    #print "levenshtein_file_file"
    file_s1_io  = open(file_s1, "rb")
    for line_s1 in file_s1_io.readlines():
        start = time.time()
        
        
        """ NUMERO DOS CAMPOS:

00 TransmissaoInicial
01 UnidadeFrequenciaTX
02 RecepcaoInicial
03 UnidadeFrequenciaRX
04 Situacao
05 CaraterSecundario
06 IndConfidencial
07 TipoClasseEstacao
08 Horarios
09 DesignacaoEmissao
10 PotenciaOperacao
11 UnidadePotencia
12 Equipamento
13 TipoAntena
14 EquipamentoAntena
15 Ganho
16 FrenteCosta
17 AnguloMeiaPotencia
18 AnguloElevacao
19 Azimute
20 VariacaoAzimutal
21 TipoPolarizacao
22 Altura
23 Raio
24 Latitude
25 Longitude
26 Altitude
27 Estacao
28 Servico
29 Indicativo
30 MedPotenciaMaxima_TR
31 MedLarguraBanda
32 DiametroSGCH
33 Diagrama
34 SiglaEstacao_TRS
35 LongitudeOrbitalSubida
36 NomeFeixeSubida
37 SiglaEstacaoDescida
38 LongitudeOrbitalDescida
39 NomeFeixeDescida
40 TipoEstacao
41 NomeEntidade
42 NumEntidade
43 NomeMunicipio
44 CodMunicipio
45 Endereco
46 UF
47 TipoClasseCorrespondencia
48 Rede
49 Distancia
50 Id

"""     #CodMunicipio/ #estacao / frequencia / endereco / azimute
        lev_cond = [[44,42],[27],[0,2],[45],[19]]



        for same_fields in lev_cond:
            print "Condicao: %s" % (same_fields)
            cmd='cat %s' % (in_file_name_2)
            for x in same_fields:
                cmd +=' | grep -F "%s"' % (line_s1.split("|")[x].replace("\n",""))
            file_s2=execServerLit(cmd)
            lev_arr=levenshtein_txt(line_s1.strip().replace("\n",""), file_s2)
            if not (lev_arr[0] == 1000): #se não encontrou vai pra proxima condicao.
                break         

        '''
        for same_fields in lev_cond:
            lev_arr =  levenshtein_file(line_s1.strip().replace("\r","").replace("\n",""), file_s2, same_fields)
            if not (lev_arr[0] == 1000): #se não encontrou vai pra proxima condicao.
                break 
        '''
           
        if not (lev_arr[0] == 0 or lev_arr[0] == 1000):
            print "Distancia: %s" % (lev_arr[0])
            print lev_arr[1]
            print line_s1
        print "(Tempo Gasto: %s)" % ((time.time() - start))





        
if __name__ == '__main__':
    if not len(sys.argv) < 2:
        
        for v in sys.argv:
            if len(v.split("="))>1:
                param = v.split("=")[0].strip()
                valor = v.split("=")[1].strip()
                try:
                    if param.lower().strip().find("days_offset")>-1:
                        days_offset = valor
                        print "days_offset: %s" % (days_offset)
                        date_now = datetime.now() - timedelta(days=(int(days_offset)))
                        in_file_name_1 = "" + date_now.strftime("%Y-%m-%d") + "_file1.txt"
                        in_file_name_2 = "" + date_now.strftime("%Y-%m-%d") + "_file2.txt"
                        export_file_id = "" + date_now.strftime("%Y-%m-%d") + "-export-db-id.txt"
                        export_file = "" + date_now.strftime("%Y-%m-%d") + "-export-db.txt"   
                        double_check_file = "" + date_now.strftime("%Y-%m-%d") + "-double_check.txt"
                    elif param.lower().strip().find("date_custom")>-1:
                        date_custom = valor
                        print "date_custom: %s" % (date_custom)
                        in_file_name_1 = "" + date_custom + "_file1.txt"
                        in_file_name_2 = "" + date_custom + "_file2.txt"
                        export_file_id = "" + date_custom + "-export-db-id.txt"
                        export_file = "" + date_custom + "-export-db.txt"   
                        double_check_file = "" + date_custom + "-double_check.txt"
                    elif param.lower().strip().find("atualizar_global")>-1:
                        atualizar_global = int(valor)
                        print "atualizar_global: %s" % (atualizar_global)
                    else:
                        eval('%s=%s' % (param,valor))   
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    print "%s:%s" % (exceptionType,exceptionValue)
    
    
    start_total = time.time()
    
    print "(Comecando!)"
    
    levenshtein_file_file(in_file_name_1,in_file_name_2)
    
    print "(Total Tempo Gasto: %s)" % ((time.time() - start_total))
